<template>
    <div id="p_taskMD">
        <div style="display:flex;border-bottom: 1px solid #eee;">
            <div style="width: 100%;overflow:scroll;-webkit-overflow-scrolling:touch;background-color:#fff;">
              <tab class="day" :style="{width: days.length*40 +'px'}" bar-active-color="#37aefc" :line-width="0">
                <tab-item :class="{today:it==today}" v-if="it<=today" :selected="daySelect === it" @on-item-click="onDay(it)" active-class="active-tab" :value="it" v-for="(it, index) in days" :key="index">{{it|dayOnly}}</tab-item>
              </tab>
            </div>
            <button-tab class="timeBtn">
                <button-tab-item @on-item-click="changeTime" selected>{{showMonth}}</button-tab-item>
            </button-tab>
        </div>
        <datetime v-show="false" :start-date="minDate" :end-date="maxDate" @on-change="monthChange" v-model="showMonth" title="日期" format="YYYY-MM" :show.sync="visibility"></datetime>
        <div id="editormd" style="display:none;">
            <textarea>{{mdcontent}}</textarea>
        </div>
        <div class="mdHTML" v-html="mdHTML">
        </div>
    </div>
</template>
<script>
import moment from "moment";
import VueMarkdown from "vue-markdown"
import axios from 'axios';
import { taskAndTag  } from "../mixin";
import { help } from "../mixinApp";
import scriptjs from 'scriptjs'

import api from '../../api';
import {
    mapState,
    mapActions
} from 'vuex'

import {
    Tab,
    TabItem,
    TransferDomDirective as TransferDom,
    Toast,
    Swipeout,
    SwipeoutItem,
    SwipeoutButton,
    XButton,
    PopupPicker,
    Group,
    Picker,
    Cell,
    Box,
      XInput,
      XTextarea,Flexbox, FlexboxItem,Datetime,
    ButtonTab,    ButtonTabItem,
    Checker,
    CheckerItem,
    Scroller,
    Sticky
} from 'vux'
export default {
    directives: {
        TransferDom
    },
    components: {VueMarkdown,
        Tab,
        TabItem,
            Toast,
            Swipeout,
            SwipeoutItem,
            SwipeoutButton,
            XButton,
        PopupPicker,
        Group,
        Picker,
            Cell,
        Box,
          XInput,
          XTextarea,Flexbox, FlexboxItem,Datetime,
        ButtonTab,    ButtonTabItem,
        Checker,
        CheckerItem,
        Scroller,
        Sticky
    },
    mixins: [taskAndTag,help],
    computed: {
        ...mapState({
            uid: state => state.vux.uid,
            minDate: state => state.z39.minDate,
            // maxDate: state => state.z39.maxDate,
            tagitemDic: state => state.z39.tagitemDic,
            taskAll: state => state.z39.taskAll,
            tagDic: state => state.z39.tagDic,
        })
    },
    watch: {
        'mdcontent':function(){
            if(!this.mdeditor){
                return ;
            }else{
                this.mdeditor.setMarkdown(this.mdcontent);
                this.renderMD('change');
            }
        }
    },
    created() {
        this.showMonth = this.showMonth || moment().format("YYYY-MM");
        this.daySelect =  moment().format("YYYY-MM-DD");
        let days = [] ,temp;
        
        let now = new Date();
        //获得某月的天数
        var getMonthDays= function (myMonth) {
            var nowYear = now.getYear();
            nowYear += (nowYear < 2000) ? 1900 : 0;
            var monthStartDate = new Date(nowYear, myMonth, 1);
            var monthEndDate = new Date(nowYear, myMonth + 1, 1);
            var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
            return days;
        }
                
        for(var i=0;i<= getMonthDays(now.getMonth()) ;i++){
            temp = (i+1) ;
            temp = temp > 9?temp:"0"+temp ;
            days.push(moment().format("YYYY-MM-") + temp);
        }
        this.days = days ;
    },
    filters: {
        dayMin: function (month) {
          return month.replace("-","")
        }  ,
        dayOnly: function (day) {
          var dayMon = moment(day) ;
          var value = dayMon.day();
          var todayStr = moment().format("YYYY-MM-DD");
          var dayDic = {1:"一",2:"二",3:"三",4:"四",5:"五",6:"六",0:"日"};
          var show = "" ;
          if( day == todayStr){
            show = "今";
          }else if(day < todayStr){
            show =  (value == 0 ||value ==6) ?dayDic[value] : dayMon.date() ;
          }else{
            show = dayMon.date() ;
          }
          return show ;
        }
    }  ,
    mounted: function() {
        scriptjs('../../../static/jslib/editormd.js', () => {
            this.initPage();
        });
    },
    methods: {
        renderMD(act){
            if(act == 'load'){
                if( this.uid== 0 ){
                    this.mdGet("/static/z39h5/default.md") ;
                }else{
                    this.daysGet({type:1,month:this.showMonth}) ;
                    this.blogGet({day:this.daySelect,content:1}) ;
                }
            }
            this.mdHTML = this.mdeditor.getPreviewedHTML();
        },
        initPage(){
            var self = this;
            if(!this.mdeditor){
                this.mdeditor = editormd({
                    id    : "editormd",
                    width : "100%",
                    height: "100%",
                    syncScrolling: "single",
                    path: "/static/lib/",
                    htmlDecode: "style,script,iframe|on*",
                    saveHTMLToTextarea: true,
                    emoji: true,
                    taskList: true,
                    fragment: true, //开启碎片图
                    tocm: true, // Using [TOCM]
                    tex: true, // 开启科学公式TeX语言支持，默认关闭
                    watch : false,                // 关闭实时预览
                    flowChart: true, // 开启流程图支持，默认关闭
                    sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
                    onlyTask: true,
                    mind: true,
                    watch:true,
                    onload : function() {
                        self.renderMD('load');
                    },
                    onchange : function() {
                        self.renderMD('change');
                    }

                });
            }
        },
        blogGet(sdata){
            if(sdata.day == this.today){
                var tasks =  this.taskAll.filter(task=> { return task.uid == this.uid && task.id && task.parid == null &&task.tags && task.tags["created"] && task.tags["created"].indexOf(this.today) >-1} );
                console.log('我是今日的所有任务',tasks)
                this.echartsTasks = tasks
                this.echartsFlag = true
                let len = tasks.length;
                if(len==0){
                    this.showDefault();
                }else{
                    this.showMdByTask(tasks);
                }
                return ;
            }
            api.blogGet(sdata).then(data => {
                if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
    				data = data.data;
                    this.mdcontent = data.content ;
    				// if(data.filename) this.mdGet(data.id) ;
    				// else this.showDefault()
                })
        },
        showDefault(){
            var tts = this.initDefaultMd();
            var dayobj = getDayMDobj([{title:"",type:"project",tasks:tts}]);
            // dataDefault.videostr + "\n"+
            this.mdcontent = dayobj.content.replace(this.today,this.daySelect) ;
        },
        blogAdd(sdata){
            let _this = this;
            api.blogAdd(sdata).then(data => {
				if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});

				data = data.data;
				this.$vux.toast.show({
					text: "添加成功",
					type: 'success'
				})
            })
        },
        blogSet(sdata){
            let _this = this;
            api.blogSet(sdata).then(data => {
                if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                    data = data.data;
                    this.$vux.toast.show({
                        text: "修改成功",
                        type: 'success'
                    })
            })
        },
        blogDel(id){
            let _this = this;
            api.blogDel({id: id}).then(data => {
                if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                    data = data.data;
                    this.$vux.toast.show({
                        text: "删除成功",
                        type: 'success'
                    })


            })
        },
        daysGet(sdata){
            let _this = this;
            api.days(sdata).then(data => {
                if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                    data = data.data;
                    this.days = data ;
                this.$nextTick(() => {
                    this.autoPos();
                });
            })
        },
        showMdByTask(tasks){
            // var tasks =
            tasks = tasks || this.taskAll.filter(task=> { return task.uid == this.uid && task.parid == null &&task.tags && task.tags["due"] && task.tags["due"].indexOf(this.today) >-1} );

            let len = tasks.length;
            let nullPro = { key: "unproject",type:"project", desc: "", title: "", tasks: [] };
            let projsDic = {} , projects =[];
            let userProjDic = {},
                userIdProjs = {};
            for (var i = 0; i <= len - 1; i++) {
                var item = Object.assign({},tasks[i]) ;
                var tempKey,tempPro; //tempPro
                item.type = "task" ;
                item.tasks = item.tasks || [] ;
                if (item.pid == null) {
                    nullPro.tasks.push(item);
                } else {
                    tempPro = projsDic[item.pid];
                    if (tempPro == undefined) {
                        projsDic[item.pid] = {tasks:[],type:"project",key:"pid"+item.pid, desc:"{desc}", title: "{title}"};
                        tempPro = projsDic[item.pid];
                        projects.push(tempPro) ;
                    }
                    tempPro.tasks = tempPro.tasks || [];
                    tempPro.tasks.push(item);
                }
            }
            projects.push(nullPro) ;
            var dayPro, mdcontent, dayobj;
            try{
                // setToday("2018-08-12")
                mdcontent = getDayMD(projects,false);
                // var dayobj = getDayMDobj([{title:"",type:"project",tasks:tts}]);
                // this.mdcontent = dayobj.content;
                // mdcontent = dayobj.content;
                this.mdcontent = mdcontent ;
            }catch(e){ console.log(e) }
            // console.log("今日日报",tasks,tasks.length,mdcontent,dayobj);
        },
        changeTime(){
            console.log("asdf");
            this.visibility = true ;
        },
        monthChange(val){
            console.log(val) ;
            var month = moment().format("YYYY-MM") ;
            if(val>month){
                this.showMonth = month ;
                return this.$vux.toast.show({text: "未来不可选" ,type: 'warn'});
            }
            this.daysGet({type:1,month:val}) ;
        },
        mdGet(path){
            if(path == this.lastPath) return;
            this.lastPath = path ;
            axios.get(path).then(response=>{
                this.mdcontent = response.data ;
                this.$vux.toast.show({text: "加载成功" ,type: 'success',time:1000});
              }).catch(error=> {
                console.log(error);
              });
        },
        onDay(day){
            this.daySelect = day ;
            this.blogGet({day,content:1}) ; //{id: id}
        },
        autoPos(){
            try{
                var x = document.querySelector("#p_taskMD div>div .today").offsetLeft ;
            document.querySelector("#p_taskMD div>div").scrollLeft = x;
            }catch(e){}
            console.log("pos:",x)
        },
        ...mapActions([

        ])
    },
    data() {
        return {
            pies:[1,2],
            echartsFlag: false,
            echartsTasks:[],
            mdcontent:"",
            days: [1,2,3,4,5,6,7,10],
              showPopupPicker: false,
              value5: ['2'],
            timeindex: 1,
            guideHeight: "500px",
            actionWeekEndArr:[] ,
            visibility: false ,
            showMonth:'',
            daySelect:"",
            weekEdit:false ,
            today: moment().format('YYYY-MM-DD'),
            lastPath:"",
            maxDate:moment().format('YYYY-MM-DD'),
            mdeditor:null,
            mdHTML:''
        }
    }
}

</script>
<style scoped lang="less">
.echart{
  background: #FFF;
  padding: 10px 10px;
}
.echart-circle{
  display: flex;
  &-item{
    flex: 1;
  }
}
.echart-title{
  font-size: 10px;
}
.add-margin{
  margin-top: 20px;
}
.daymd{
    padding: 0 4px;
}

.day-item {
  border: 1px solid #ececec;
  padding: 5px 15px;
}
.day-item-selected {
  border: 1px solid green;
}

.weui-cell img {
    max-width: 100px;
    height: 44px;
    margin-right: 10px;
    width: auto;
}

#p_taskMD .vux-button-group{
    background-color: #fff;
    padding-top: 1px;
}
#p_taskMD .timeBtn{width:70px;}
#p_taskMD .vux-tab {
    padding:2px 6px ;
    height: 32px;
}
#p_taskMD .vux-tab .vux-tab-item{
    background: #fff;
    line-height: 28px;    font-size: 16px;
}
#p_taskMD .vux-tab .vux-tab-selected {
    background: rgba(0, 169, 255, 0.24);border-radius: 6px;
}

</style>
<style>
#p_taskMD .daymd{
    overflow-x:hidden;
}

#p_taskMD .daymd img{
    max-width: 100%;
}
#p_taskMD .weui-cells {
    margin-top: 0px;
}

#p_taskMD .weui-search-bar:before {
    height: 0;
    border-top: 0;
}
/*#p_taskMD .vux-tab .vux-tab-item{
    background: #fff;
}*/
#p_taskMD .day  .vux-tab-selected {
    background: #eee;
    border-radius: 4px;
}
.scrollable .vux-tab-item{
    flex:1;
}
.mdHTML{
    background: #fff;
    padding: 10px;
}
</style>
